<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <!-- <el-form-item label="输入搜索" prop="id">
        <el-input v-model="queryParams.id" placeholder="订单编号" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="商品类别" prop="productType">
        <el-select v-model="queryParams.productType" placeholder="全部" clearable>
          <el-option v-for="dict in dict.type.product_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="商品标题" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌选择" prop="brandId">
        <el-select v-model="queryParams.brandId" placeholder="请选择品牌" clearable filterable @change="handleBrandChange">
          <el-option v-for="brand in brandList" :key="brand.id" :label="brand.brand" :value="brand.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="区域选择" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择区域" clearable filterable @change="handleAreaChange">
          <el-option v-for="area in areaList" :key="area.id" :label="area.area" :value="area.id" />
        </el-select>
      </el-form-item>

      <!-- 新增限时特价筛选 -->
      <el-form-item label="限时特价" prop="isSpecial">
        <el-select v-model="queryParams.isSpecial" placeholder="全部" clearable>
          <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!-- 新增新品推荐筛选 -->
      <el-form-item label="新品推荐" prop="isNew">
        <el-select v-model="queryParams.isNew" placeholder="全部" clearable>
          <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!-- 新增爆品推荐筛选 -->
      <el-form-item label="爆品推荐" prop="isHot">
        <el-select v-model="queryParams.isHot" placeholder="全部" clearable>
          <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!-- 新增可用积分筛选 -->
      <el-form-item label="可用积分" prop="isScore">
        <el-select v-model="queryParams.isScore" placeholder="全部" clearable>
          <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item class="search">
        <hide-search :show-search.sync="showSearch"></hide-search>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="table-content">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['project:product:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['project:product:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['project:product:remove']">删除</el-button>
        </el-col>
        <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
      </el-row>

      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="商品类别" align="center" prop="productType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_type" :value="scope.row.productType" />
          </template>
        </el-table-column>
        <el-table-column label="商品标题" align="center" prop="title" />
        <el-table-column label="商品主图" align="center" width="120">
          <template slot-scope="scope">
            <el-image v-if="scope.row.mainImage" :src="scope.row.mainImage" :preview-src-list="[scope.row.mainImage]"
              style="width: 60px; height: 60px" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" align="center" prop="price" :show-overflow-tooltip="true" />
        <el-table-column label="下划价" align="center" prop="underlinePrice" :show-overflow-tooltip="true" />
        <el-table-column label="销量" align="center" prop="saleNum" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="库存" align="center" prop="inventory" />
        <!-- 新增轮播图媒体列 -->
        <el-table-column label="轮播图媒体" align="center" prop="cyclePath" width="200">
          <template slot-scope="scope">
            <div class="media-list" v-if="scope.row.cyclePath">
              <div v-for="(media, index) in parseMediaList(scope.row.cyclePath)" :key="index" class="media-item"
                @click="previewMedia(media)">
                <!-- 图片类型 -->
                <div v-if="isImage(media.url)" class="media-wrapper image-type">
                  <img :src="media.url" class="media-thumbnail" />
                  <div class="media-type-badge image-badge">
                    <i class="el-icon-picture"></i>
                    <span>图片</span>
                  </div>
                </div>
                <!-- 视频类型 -->
                <div v-else-if="isVideo(media.url)" class="media-wrapper video-type">
                  <video :src="media.url" class="media-thumbnail" muted></video>
                  <div class="media-type-badge video-badge">
                    <i class="el-icon-video-camera"></i>
                    <span>视频</span>
                  </div>
                  <div class="video-play-icon">
                    <i class="el-icon-video-play"></i>
                  </div>
                </div>
              </div>
              <div v-if="parseMediaList(scope.row.cyclePath).length === 0" class="no-media">
                暂无媒体
              </div>
            </div>
            <div v-else class="no-media">
              暂无媒体
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="商品详情" align="center" prop="productDesc" />
         <el-table-column label="商品溯源" align="center" prop="source" />
          <el-table-column label="商品授权" align="center" prop="credential" /> -->
        <el-table-column label="品牌id" align="center" prop="brandId" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="区域id" align="center" prop="areaId" />
        <el-table-column label="区域" align="center" prop="area" />
        <el-table-column label="详细区域" align="center" prop="areaAddr" />
        <!-- 新增服务选项列 -->
        <el-table-column label="服务选项" align="center" prop="service" width="200">
          <template slot-scope="scope">
            <div class="service-tags" v-if="scope.row.service">
              <el-tag v-for="(service, index) in parseServiceString(scope.row.service)" :key="index"
                :type="getServiceTagType(index)" size="mini" class="service-tag">
                {{ service }}
              </el-tag>
            </div>
            <span v-else class="no-service">暂无服务</span>
          </template>
        </el-table-column>
        <el-table-column label="限时特价" align="center" prop="isSpecial">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isSpecial" />
          </template>
        </el-table-column>
        <!-- 新增新品推荐列 -->
        <el-table-column label="新品推荐" align="center" prop="isNew">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isNew" />
          </template>
        </el-table-column>
        <!-- 新增爆品推荐列 -->
        <el-table-column label="爆品推荐" align="center" prop="isHot">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isHot" />
          </template>
        </el-table-column>
        <!-- 新增是否可用积分列 -->
        <el-table-column label="可用积分" align="center" prop="isScore">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isScore" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['project:product:edit']">修改</el-button>
            <el-button size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)" class="btn-delete"
              v-hasPermi="['project:product:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 媒体预览对话框 -->
      <el-dialog title="媒体预览" :visible.sync="mediaPreviewVisible" width="60%" append-to-body>
        <div class="media-preview-container">
          <img v-if="previewMediaItem && isImage(previewMediaItem.url)" :src="previewMediaItem.url"
            class="preview-image" />
          <video v-else-if="previewMediaItem && isVideo(previewMediaItem.url)" :src="previewMediaItem.url"
            class="preview-video" controls autoplay></video>
        </div>
      </el-dialog>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="商品类别" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择商品类别" clearable style="width: 100%">
            <el-option v-for="dict in dict.type.product_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="商品主图" prop="mainImage">
          <imageUpload v-model="form.mainImage" :limit="1" :return-url="true" />
        </el-form-item>
        <el-form-item label="商品轮播图" prop="cyclePath">
          <media-upload v-model="form.cyclePath" :limit="5" :return-url="true" @change="handleMediaChange" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :min="0" placeholder="请输入商品价格" style="width: 100%" />
        </el-form-item>
        <el-form-item label="下划价" prop="underlinePrice">
          <el-input-number v-model="form.underlinePrice" :precision="2" :min="0" placeholder="请输入下划价" style="width: 100%" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input-number v-model="form.inventory" :precision="2" :min="0" placeholder="请输入库存" style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品详情" prop="productDesc">
          <editor v-model="form.productDesc" :min-height="192"/>
        </el-form-item>

        <!-- 新增商品溯源字段 -->
        <el-form-item label="商品溯源" prop="source">
          <media-upload v-model="form.source" :limit="5" :return-url="true" @change="handleMediaChange" />
        </el-form-item>

        <!-- 新增商品商品授权字段 -->
        <el-form-item label="商品授权" prop="credential">
          <media-upload v-model="form.credential" :limit="5" :return-url="true" @change="handleMediaChange" />
        </el-form-item>

        <!-- 品牌选择区域 -->
        <el-form-item label="品牌选择" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择品牌" clearable filterable @change="handleBrandChange">
            <el-option v-for="brand in brandList" :key="brand.id" :label="brand.brand" :value="brand.id" />
          </el-select>
        </el-form-item>

        <!-- 区域选择区域 -->
        <el-form-item label="区域选择" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择区域" clearable filterable @change="handleAreaChange">
            <el-option v-for="area in areaList" :key="area.id" :label="area.area" :value="area.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域详情" prop="areaAddr">
          <el-input v-model="form.areaAddr" placeholder="区域详情" readonly />
        </el-form-item>

        <!-- 新增服务选项字段 -->
        <el-form-item label="服务选项" prop="service">
          <el-checkbox-group v-model="form.serviceArray" @change="handleServiceChange">
            <el-checkbox label="包邮">包邮</el-checkbox>
            <el-checkbox label="正品保证">正品保证</el-checkbox>
            <el-checkbox label="可退可换">可退可换</el-checkbox>
            <el-checkbox label="产地溯源">产地溯源</el-checkbox>
            <el-checkbox label="质量检测">质量检测</el-checkbox>
            <el-checkbox label="急速发货">急速发货</el-checkbox>
            <el-checkbox label="售后保障">售后保障</el-checkbox>
            <el-checkbox label="分期付款">分期付款</el-checkbox>
            <el-checkbox label="礼品包装">礼品包装</el-checkbox>
            <el-checkbox label="保修服务">保修服务</el-checkbox>
          </el-checkbox-group>
          <div class="service-tip">
            <i class="el-icon-info"></i>
            <span>选择适用的服务选项，将在商品详情页展示给用户</span>
          </div>
          <!-- 隐藏的输入框，用于存储逗号分隔的字符串 -->
          <el-input v-model="form.service" type="hidden" />
        </el-form-item>
        <el-form-item label="限时特价">
          <el-radio-group v-model="form.isSpecial">
            <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 新增新品推荐表单项 -->
        <el-form-item label="新品推荐">
          <el-radio-group v-model="form.isNew">
            <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 新增爆品推荐表单项 -->
        <el-form-item label="爆品推荐">
          <el-radio-group v-model="form.isHot">
            <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 新增是否可用积分表单项 -->
        <el-form-item label="可用积分">
          <el-radio-group v-model="form.isScore">
            <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, exportProduct, getProduct, addProduct, updateProduct, delProduct } from "@/api/product";
import { listBrand } from '@/api/brand';
import { listArea } from '@/api/area';
import MediaUpload from '@/components/MediaUpload';
import Editor from '@/components/Editor';

export default {
  name: "Product",
  components: {
    MediaUpload,
    Editor
  },
  dicts: ['sys_yes_no', 'product_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 参数表格数据
      productList: [],
      areaList: [],
      brandList: [],
      // 媒体预览相关
      mediaPreviewVisible: false,
      previewMediaItem: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productType: undefined,
        title: undefined,
        mainImage: undefined,
        cyclePath: undefined,
        price: undefined,
        underlinePrice: undefined,
        unit: undefined,
        inventory: undefined,
        productDesc: undefined,
        source: undefined,        // 新增
        credential: undefined,    // 新增
        brandId: undefined,
        brand: undefined,
        areaId: undefined,
        area: undefined,
        areaAddr: undefined,
        service: undefined,
        isSpecial: undefined,
        isNew: undefined,     // 新增新品推荐查询参数
        isHot: undefined,     // 新增爆品推荐查询参数
        isScore: undefined,   // 新增是否可用积分查询参数
      },
      // 表单参数
      form: {},
      // 服务选项的标签类型配置
      serviceTagTypes: ['success', 'primary', 'warning', 'info', 'danger'],
      // 表单校验
      rules: {
        productType: [
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        mainImage: [
          { required: true, message: "商品主图不能为空", trigger: "blur" }
        ],
        cyclePath: [
          { required: true, message: "轮播图媒体不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        underlinePrice: [
          { required: true, message: "划线价不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        inventory: [
          { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        productDesc: [
          { required: true, message: "商品详情不能为空", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "区域ID不能为空", trigger: "blur" }
        ],
        area: [
          { required: true, message: "区域不能为空", trigger: "change" }
        ],
        areaAddr: [
          { required: true, message: "详细区域不能为空", trigger: "blur" }
        ],
        mainImages: [
          { required: true, message: "请至少上传一张商品主图", trigger: "change" }
        ]
      },
      // 服务选项的标签类型配置
      serviceTagTypes: ['success', 'primary', 'warning', 'info', 'danger']
    };
  },
  created() {
    this.getList();
    this.loadBrandList();
    this.loadAreaList();
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        console.log("response ---- ", response)
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 加载品牌列表
    async loadBrandList() {
      try {
        const response = await listBrand({ pageNum: 1, pageSize: 1000 });
        if (response.code === 200) {
          this.brandList = response.rows;
        }
      } catch (error) {
        console.error('加载品牌列表失败:', error);
      }
    },

    // 加载区域列表
    async loadAreaList() {
      try {
        const response = await listArea({ pageNum: 1, pageSize: 1000 });
        if (response.code === 200) {
          this.areaList = response.rows;
        }
      } catch (error) {
        console.error('加载区域列表失败:', error);
      }
    },

    // 品牌选择变化 - 联动更新品牌ID和品牌名称
    handleBrandChange(brandId) {
      if (brandId) {
        const selectedBrand = this.brandList.find(brand => brand.id === brandId);
        if (selectedBrand) {
          this.form.brandId = selectedBrand.id;
          this.form.brand = selectedBrand.brand;
        }
      } else {
        this.form.brandId = undefined;
        this.form.brand = undefined;
      }
    },

    // 区域选择变化 - 联动更新区域ID、区域名称和区域详情
    handleAreaChange(areaId) {
      if (areaId) {
        const selectedArea = this.areaList.find(area => area.id === areaId);
        if (selectedArea) {
          this.form.areaId = selectedArea.id;
          this.form.area = selectedArea.area;
          this.form.areaAddr = selectedArea.areaDetail || selectedArea.areaAddr || '';
        }
      } else {
        this.form.areaId = undefined;
        this.form.area = '';
        this.form.areaAddr = '';
      }
    },

    // 媒体变化处理
    handleMediaChange(mediaList) {
      console.log('轮播图媒体变化:', mediaList);
      // 可以在这里处理媒体变化的逻辑
    },

    // 解析服务列表
    parseServiceList(service) {
      if (!service) return [];

      let serviceArray = [];
      try {
        // 如果是字符串，尝试解析为JSON数组
        if (typeof service === 'string') {
          serviceArray = JSON.parse(service);
        } else if (Array.isArray(service)) {
          serviceArray = service;
        }
      } catch (error) {
        console.error('解析服务列表失败:', error);
        return [];
      }

      // 将服务值映射为标签
      return serviceArray.map(serviceValue => {
        const serviceOption = this.serviceOptions.find(option => option.value === serviceValue);
        return serviceOption || { value: serviceValue, label: serviceValue, type: 'info' };
      });
    },

    // 获取服务标签类型
    getServiceTagType(serviceValue) {
      const serviceOption = this.serviceOptions.find(option => option.value === serviceValue);
      return serviceOption ? serviceOption.type : 'info';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productType: undefined,
        title: undefined,
        mainImage: undefined,
        cyclePath: undefined,
        price: undefined,
        underlinePrice: undefined,
        unit: undefined,
        inventory: undefined,
        productDesc: undefined,
        brandId: undefined,
        brand: undefined,
        areaId: undefined,
        area: undefined,
        areaAddr: undefined,
        service: '', // 改为空字符串
        serviceArray: [], // 改为空数组，确保响应式
        isSpecial: undefined,
        isNew: undefined,     // 新增新品推荐字段
        isHot: undefined,     // 新增爆品推荐字段
        isScore: undefined,   // 新增是否可用积分字段
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加参数";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 假设这里有获取产品详情的逻辑
      getProduct(row.id).then(response => {
        this.form = response.data;
        // 使用$set确保响应式
        this.$set(this.form, 'serviceArray', this.serviceStringToArray(this.form.service || ''));
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        console.log("valid ---- ", valid)
        if (valid) {
          console.log("form ---- ", this.form)
          if (this.form.id != undefined) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
    // 解析媒体列表
    parseMediaList(cyclePath) {
      if (!cyclePath) return [];

      try {
        // 如果是字符串，尝试解析为JSON
        if (typeof cyclePath === 'string') {
          // 处理逗号分隔的URL字符串
          if (cyclePath.includes(',')) {
            return cyclePath.split(',').map((url, index) => ({
              url: url.trim(),
              type: this.getMediaType(url.trim()),
              index
            }));
          }

          // 单个URL
          return [{
            url: cyclePath,
            type: this.getMediaType(cyclePath),
            index: 0
          }];
        }

        // 如果已经是数组
        if (Array.isArray(cyclePath)) {
          return cyclePath.map((item, index) => ({
            url: typeof item === 'string' ? item : item.url,
            type: this.getMediaType(typeof item === 'string' ? item : item.url),
            index
          }));
        }

        return [];
      } catch (error) {
        console.error('解析媒体列表失败:', error);
        return [];
      }
    },

    // 获取媒体类型
    getMediaType(url) {
      if (!url) return 'unknown';
      const extension = url.split('.').pop().toLowerCase();
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'];

      if (imageExtensions.includes(extension)) {
        return 'image';
      } else if (videoExtensions.includes(extension)) {
        return 'video';
      }
      return 'unknown';
    },

    // 判断是否为图片
    isImage(url) {
      return this.getMediaType(url) === 'image';
    },

    // 判断是否为视频
    isVideo(url) {
      return this.getMediaType(url) === 'video';
    },

    // 预览媒体
    previewMedia(media) {
      this.previewMediaItem = media;
      this.mediaPreviewVisible = true;
    },

    // 处理服务选项变化
    handleServiceChange(selectedServices) {
      // 将选中的服务数组转换为逗号分隔的字符串
      console.log('selectedServices ---:', selectedServices);
      this.form.service = selectedServices.join(',');
      console.log('服务选项变化:', this.form.service);
    },

    // 解析服务字符串为数组
    parseServiceString(serviceString) {
      if (!serviceString || serviceString.trim() === '') {
        return [];
      }
      // 按逗号分割字符串，并去除空白字符
      return serviceString.split(',').map(item => item.trim()).filter(item => item !== '');
    },

    // 获取服务标签类型（循环使用不同颜色）
    getServiceTagType(index) {
      return this.serviceTagTypes[index % this.serviceTagTypes.length];
    },

    // 将服务字符串转换为数组（用于编辑时回显）
    serviceStringToArray(serviceString) {
      if (!serviceString || serviceString.trim() === '') {
        return [];
      }
      return serviceString.split(',').map(item => item.trim()).filter(item => item !== '');
    },
  }
};
</script>

<style scoped>
.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
}

.media-item {
  position: relative;
  cursor: pointer;
  transition: transform 0.2s;
}

.media-item:hover {
  transform: scale(1.05);
}

.media-wrapper {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  border: 2px solid #ddd;
}

.media-wrapper.image-type {
  border-color: #67c23a;
}

.media-wrapper.video-type {
  border-color: #409eff;
}

.media-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.media-type-badge {
  position: absolute;
  top: 2px;
  right: 2px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 10px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.image-badge {
  background: rgba(103, 194, 58, 0.9);
}

.video-badge {
  background: rgba(64, 158, 255, 0.9);
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 20px;
  text-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
}

.no-media {
  color: #999;
  font-size: 12px;
  text-align: center;
  padding: 20px 0;
}

.media-preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.preview-video {
  max-width: 100%;
  max-height: 500px;
}

/* 服务选项样式 */
.service-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.service-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-height: 80px;
  overflow-y: auto;
}

.service-tag {
  margin: 0;
  font-size: 11px;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-service {
  color: #999;
  font-size: 12px;
}

/* 多选框组样式 */
.el-checkbox-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fafafa;
}

.el-checkbox {
  margin: 0;
  white-space: nowrap;
}
</style>
